package com.wxd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxd.entity.Admin;
import com.wxd.entity.Student;
import com.wxd.entity.Teacher;
import com.wxd.service.AdminService;
import com.wxd.service.StudentService;
import com.wxd.service.TeacherService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource private TeacherService ts;
    @Resource private StudentService ss;
    @Resource private AdminService as;
    @GetMapping("/login")
    public boolean login(String name, String pwd, int role, HttpSession session){
        Object one=null;
        if(role==1){
            QueryWrapper<Student> wrapper = new QueryWrapper<>();
            wrapper.eq("name",name).eq("pwd",pwd);
            one=ss.getOne(wrapper);
        }
        if(role==2){
            QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
            wrapper.eq("name",name).eq("pwd",pwd);
            one=ts.getOne(wrapper);
        }
        if(role==3){
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            wrapper.eq("name",name).eq("pwd",pwd);
            one=as.getOne(wrapper);
        }
        if(one!=null){
            session.setAttribute("user",one);
        }
        return one!=null;
    }
    @PutMapping("/updatePwd")
    public void updatePwd(Integer role,String pwd,HttpSession session){
        if(role==1){
            Student stu = (Student) session.getAttribute("user");
            stu.setPwd(pwd);
            ss.updateById(stu);
            session.setAttribute("user",stu);
        }
        if(role==2){
            Teacher tea = (Teacher) session.getAttribute("user");
            tea.setPwd(pwd);
            ts.updateById(tea);
            session.setAttribute("user",tea);
        }
        if(role==3){
            Admin ad = (Admin) session.getAttribute("user");
            ad.setPwd(pwd);
            as.updateById(ad);
            session.setAttribute("user",ad);
        }
    }
}
